﻿using HCDV;
using HCDV.HCSP;
using hcrainMvc.ashx.ywfunction;
using hrainwebbase.ashx.spfunction;
//using hcrainMvc.BLL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Http;

namespace hcrainMvc.Controllers
{
    public class TaskController : ApiController
    {

        /// <summary>
        /// 统计任务
        /// </summary>
        /// <returns></returns>
        [ActionName("GetDayTask")]
        [HttpGet]
        public void GetDayTask()
        {

            try
            {
                using (dbsimple db = new dbsimple())
                {
                    //生成昨天的 中心原料库-库存
                    db.exe(@"Insert into table中心原料库历史库存(databranchid,productstate,productid,taskfromorgid,taskfromorgname
,inouttype,storeall,hasoutall,nowstore,storeallok,storefortype1,storefortype2,storefortype3,storefortype4,storefortype5,daynow,addtime) 
select databranchid,productstate,productid,taskfromorgid,taskfromorgname
,inouttype,storeall,hasoutall,nowstore,storeallok,storefortype1,storefortype2,storefortype3,storefortype4,storefortype5,date_format( (now() + interval -(1) day),'%Y-%m-%d'),NOW() from work原料库实时库存");
                }
            }
            catch (Exception)
            { }

            try
            {
                using (dbsimple db = new dbsimple())
                {
                    //生成昨天的 中心原料库-库存
                    db.exe(@"Insert into table中心成品库历史库存(databranchid,productstate,productid,taskfromorgid,taskfromorgname
,inouttype,storeall,hasoutall,nowstore,storeallok,storefortype1,storefortype2,storefortype3,storefortype4,storefortype5,daynow,addtime) 
select databranchid,productstate,productid,taskfromorgid,taskfromorgname
,inouttype,storeall,hasoutall,nowstore,storeallok,storefortype1,storefortype2,storefortype3,storefortype4,storefortype5,date_format( (now() + interval -(1) day),'%Y-%m-%d'),NOW() from work成品库实时库存");
                }
            }
            catch (Exception)
            { }


        }
        /// <summary>
        /// 任务-修复库存
        /// </summary>
        /// <returns></returns>
        [ActionName("GetStoreTask")]
        [HttpGet]
        public void GetStoreTask()
        {

            try
            {
                using (dbsimple db = new dbsimple())
                {
                    var dt = db.Query(@"SELECT storeid,spid,sum(endallcount) as endallcount  from herp_inoutorderlistview where endallcount>=0 and datastate='入库' and dataisdeleted=0 GROUP BY storeid,spid");
                    foreach (DataRow dr in dt.Rows)
                    {
                        db.SpExe(string.Format("update herp_store set endallcount= {0} where storehouseid={1} and productid={2}", dr["endallcount"].ToString(), dr["storeid"].ToString(), dr["spid"].ToString()));
                    }

                }
            }
            catch (Exception)
            { }

        }
        /// <summary>
        /// 任务-更新发货汇总表
        /// </summary>
        /// <returns></returns>
        [ActionName("GetReSetOutInfoToCenter")]
        [HttpGet]
        public string GetReSetOutInfoToCenter(string databranchid, string day = null, bool ismanage = false)
        {
            //return BsForApi.JDBs.GetReSetOutInfoToCenter(databranchid,day,ismanage);

            if (day == null)
                day = DateTime.Now.ToString("yyyy-MM-dd");
            string sql = @"insert into hsc_task_store_out_group
(
select id,outgid,inouttype,outdesc,taskid,taskno,tasklistid,taskworktime,taskfromorgid,taskfromorgname,dkname,dkid,storehouseid,
productid,productgid,productname,SUM(storeall) storeall,SUM(storefortype1) as storefortype1,SUM(storefortype2) as storefortype2,SUM(storefortype3) as storefortype3,
storealluseall,price,hasoutall,unit,jgcount,owneruserid,lockcout,outstate,jjuserid,jjusername,productstate,'待质检',dataadduserid,datadepid,databranchid,
datadepname,databranchname,dataaddusername,datafromtable,datafromkeyid,datafromdesc,endtime,
date_format(dataaddtime,'%Y-%m-%d 00:00:00') as dataaddtime ,
storefortype1out,storefortype2out,storefortype3out,storefortype4out,storefortype5out,moneycount,
SUM(storefortype4) storefortype4,
SUM(storefortype5) storefortype5,carid,carinfo,0,sum(storeksall) storeksall,csgetpc,'否'
from hsc_task_store_out
 where    
dataaddtime>='{1} 00:00:00' and dataaddtime<'{1} 23:59:59'  and taskfromorgid ={0} and 
 inoutstorestate in('待入库','入库中') and inouttype in('发往加工中心','发货记录登记')   
GROUP BY taskid,taskfromorgid,productid,date_format(dataaddtime,'%Y-%m-%d 00:00:00'),productstate,csgetpc
)";
            sql = string.Format(sql, databranchid, day);

            try
            {
                using (dbsimple db = new dbsimple())
                {
                    //先删除
                    db.SpExe(string.Format("DELETE from    hsc_task_store_out_group where taskfromorgid={0} and dataaddtime='{1} 00:00:00' and inoutstorestate='待质检'", databranchid, day));
                    //再插入
                    db.SpExe(sql);


                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "处理成功";

        }
        /// <summary>
        /// 任务-分本码段
        /// </summary>
        /// <returns></returns>
        [ActionName("GetFPCode")]
        [HttpGet]
        public void GetFPCode(string frombranchid, string day)
        {
            var insertsql = @"INSERT INTO hsc_task_process_workok_code(endcodel,startcodel,startcoden,taskid,endcode,dkid,endcodes,dataaddtime,
dkname,dataaddusername,startcodes,taskworktime,taskfromorgname,productname,productid,datadepid,datadepname,taskno,taskfromorgid,startcode,
databranchid,dataadduserid,databranchname,endcoden,csgetpc,productstate,codecount,inouttype) 
            VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}',
'{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}',{26},'入库后分配')";
            string doids = "";

            using (dbsimple db = new dbsimple())
            {
                var dt = db.Query(
string.Format(@"SELECT a.*,b.codecount  已预分配数量  from hsc_task_store_process a  left join hsc_task_process_workok_code  b on a.csgetpc=b.csgetpc and a.productstate=b.productstate
   where a.taskfromorgid={0}  and   a.dataaddtime<='{1}' and  ( a.codestate='待分配' or  a.codestate='无法分配' )  and a.inouttype='运输入库'
and a.dataaddtime>'2018-09-23' and a.codecount>0 and (b.inouttype='预分配' or b.inouttype is null)", frombranchid, day + " 23:59:59"));
                foreach (DataRow dr in dt.Rows)
                {
                    if (doids.IndexOf(dr["id"].ToString()) >= 0)
                    {
                        db.SpExe("update hsc_task_store_process set  codestate='不能重复分配' where id= " + dr["id"].ToString());
                        continue;
                    }
                    doids += dr["id"].ToString() + " ";

                    double codecount = 1;
                    if (!string.IsNullOrEmpty(dr["已预分配数量"].ToString()))
                    {
                        codecount = double.Parse(dr["codecount"].ToString()) - double.Parse(dr["codecounthasfp"].ToString()) - double.Parse(dr["已预分配数量"].ToString());
                    }
                    else
                    {
                        codecount = double.Parse(dr["codecount"].ToString()) - double.Parse(dr["codecounthasfp"].ToString());
                    }
                    if (codecount == 0)
                    {
                        db.SpExe("update hsc_task_store_process set  codestate='不用分配' where id= " + dr["id"].ToString());
                        continue;
                    }
                    //获取分配
                    var codelist = ywfunction.GetOutCodeList("150", dr["productid"].ToString(), codecount);
                    bool hasfp = false;
                    double allcount = 0;
                    foreach (var codesb in codelist)
                    {
                        var codes = ywfunction.ReSetCodeInfo(codesb);
                        if (!string.IsNullOrEmpty(codes.startCode))
                        {
                            hasfp = true;
                            string insertsqlr = string.Format(insertsql,
                                codes.NumLenth,
                                codes.NumLenth,
                                codes.startNum,
                                dr["taskid"].ToString(),
                                codes.endCode,
                                dr["dkid"].ToString(),
                                codes.codeString,
                                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                 dr["dkname"].ToString(),
                                 "sys",
                                codes.codeString,
                                  dr["dataaddtime"].ToString(),
                                   dr["taskfromorgname"].ToString(),
                                       dr["productname"].ToString(),
                                             dr["productid"].ToString(),
                                               "0", "sys",
                                                 dr["taskno"].ToString(),
                                                   dr["taskfromorgid"].ToString(), codes.startCode,
                                                    "0",
                                                     "0",
                                                      "0", codes.endNum, dr["csgetpc"].ToString(), dr["productstate"].ToString(), (codes.endNum - codes.startNum + 1)
                                   );
                            allcount += (codes.endNum - codes.startNum + 1);
                            db.SpExe(insertsqlr);

                        }

                    }
                    if (hasfp)
                    {
                        db.SpExe("update hsc_task_store_process set  codestate='已分配',codecounthasfp=codecounthasfp+" + allcount + " where id= " + dr["id"].ToString());
                        ywfunction.PostOutCodeListIsOk(codelist);
                    }


                }

            }


        }

        /// <summary>
        /// 已发货-预分配本码段
        /// </summary>
        /// <returns></returns>
        [ActionName("GetPlantFPCode")]
        [HttpGet]
        public void GetPlantFPCode(string brandid, string day, string frombranchid)
        {
            var insertsql = @"INSERT INTO hsc_task_process_workok_code(endcodel,startcodel,startcoden,taskid,endcode,dkid,endcodes,dataaddtime,
dkname,dataaddusername,startcodes,taskworktime,taskfromorgname,productname,productid,datadepid,datadepname,taskno,taskfromorgid,startcode,
databranchid,dataadduserid,databranchname,endcoden,csgetpc,productstate,codecount,inouttype) 
            VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}',
'{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}',{26},'预分配')";


            using (dbsimple db = new dbsimple())
            {
                var dt = db.Query(string.Format(@"select a.*,t.nv1,t.nv2 from hsc_task_store_out_group a left join yw_baseinfo as t on a.productid  =t.id where 
 a.taskfromorgid={1}    and 
 a.inouttype in('发往加工中心','发货记录登记')   
and a.dataaddtime>='{0} 00:00:00' and a.dataaddtime<='{0} 23:59:59' 
and a.inoutstorestate in ('待入库', '入库中','待质检')  and a.storeall>a.hasoutall and a.hasplantcode='否'", day,frombranchid));
                foreach (DataRow dr in dt.Rows)
                {
                    double codecount = 1;
                    if (dr["productstate"].ToString() == "原料")
                        codecount = (int)(double.Parse(dr["storeall"].ToString()) * double.Parse(dr["nv1"].ToString()) * 0.9);
                    else codecount = (int)(double.Parse(dr["storeall"].ToString()) * double.Parse(dr["nv2"].ToString()) * 0.9);

                    //获取分配
                    var codelist = ywfunction.GetOutCodeList("150", dr["productid"].ToString(), codecount);
                    bool hasfp = false;
                    foreach (var codesb in codelist)
                    {
                        var codes = ywfunction.ReSetCodeInfo(codesb);
                        if (!string.IsNullOrEmpty(codes.startCode))
                        {
                            hasfp = true;
                            string insertsqlr = string.Format(insertsql,
                                codes.NumLenth,
                                codes.NumLenth,
                                codes.startNum,
                                dr["taskid"].ToString(),
                                codes.endCode,
                                dr["dkid"].ToString(),
                                codes.codeString,
                                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                 dr["dkname"].ToString(),
                                 "sys",
                                codes.codeString,
                                  dr["dataaddtime"].ToString(),
                                   dr["taskfromorgname"].ToString(),
                                       dr["productname"].ToString(),
                                             dr["productid"].ToString(),
                                               "0", "sys",
                                                 dr["taskno"].ToString(),
                                                   dr["taskfromorgid"].ToString(), codes.startCode,
                                                    "0",
                                                     "0",
                                                      "0", codes.endNum, dr["csgetpc"].ToString(), dr["productstate"].ToString(), (codes.endNum - codes.startNum + 1)
                                   );
                            db.SpExe(insertsqlr);

                        }

                    }
                    if (hasfp)
                    {
                        db.SpExe("update hsc_task_store_out_group set  hasplantcode='是' where id= " + dr["id"].ToString());
                        ywfunction.PostOutCodeListIsOk(codelist);
                    }


                }

            }



        }

    }



}
